package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.RaceInfoResponse
import com.gexiaobao.pigeon.app.model.bean.VisitMemberListResponse
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentOrgPassBinding
import com.gexiaobao.pigeon.ui.adapter.OrgPassAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogMemberList
import com.gexiaobao.pigeon.ui.dialog.RxDialogPlayBack
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPassDetail
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPigeonGatheringDetail
import com.gexiaobao.pigeon.ui.fragment.mine.organization.video.ActivityCarLiveAndPlayBack
import com.gexiaobao.pigeon.ui.fragment.mine.organization.video.ActivityGatherLive
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import me.hgj.jetpackmvvm.util.startActivity


/**
 * @Author      : hxw
 * @Date        : 2024/5/23 15:31
 * @Describe    : 关卡列表
 */
class FragmentOrgPass : BaseFragment<OrgDetailViewModel, FragmentOrgPassBinding>() {

    private var backLiveStatus = 0
    private var carLiveStatus = 0
    private var gatherLiveStatus = 0
    private var passName: String = ""
    private val mAdapter: OrgPassAdapter by lazy { OrgPassAdapter(arrayListOf()) }
    private var raceInfo: ArrayList<RaceInfoResponse.PassListBean> = arrayListOf()

    private var passId = 0
    private var mRaceId = 0
    private var passCreateType = 0//2科汇
    private var passType = 0//1-比赛，其它-训放
    private var mOrgIcon = ""
    private var mOrgName = ""
    private var mOrgRaceName = ""
    private var passStatus = ""
    private var pressedType = ""
    private var memberList: ArrayList<VisitMemberListResponse.ListBean> = arrayListOf()

    private var sharedViewModel: SharedViewModel? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        sharedViewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initView(savedInstanceState: Bundle?) {

        /** 初始化recycleView */
        mDatabind.recyclerViewPass.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 12f))
        )
        mDatabind.recyclerViewPass.adapter = mAdapter

        sharedViewModel?.orgInfoBean?.observe(viewLifecycleOwner) {
            mRaceId = it.raceId
            mOrgIcon = it.icon
            mOrgName = it.orgName
            mOrgRaceName = it.raceName
        }

        /** 接收父fragment传递过来的数据 */
        sharedViewModel?.raceInfoData?.observe(viewLifecycleOwner) {
            raceInfo.clear()
            raceInfo.addAll(it.passList)
            mAdapter.setList(it.passList)
            mAdapter.notifyDataSetChanged()
            mDatabind.includeEmptyView.llEmptyData.isVisible = it.isEmpty()
            mDatabind.recyclerViewPass.isVisible = !it.isEmpty()

        }
        sharedViewModel?.memberInfoListData?.observe(viewLifecycleOwner) {
            memberList.clear()
            memberList.addAll(it)
        }

        mAdapter.addChildClickViewIds(
            R.id.llItemRaceLiveStatus,
            R.id.tvItemOrgPassGatherCount,
            R.id.tvVideoPlayBack
        )
        mAdapter.setOnItemChildClickListener { _, view, position ->
            passId = mAdapter.data[position].id
            passName = mAdapter.data[position].passName
            when (view.id) {
                R.id.tvVideoPlayBack -> {//1-直播，2-关卡详情，3-视频回放，4-集鸽详情
                    pressedType = "3"
                    goToPassDetail(position)
                }

                R.id.tvItemOrgPassGatherCount -> {
                    pressedType = "4"
                    goToPassDetail(position)
                }

                R.id.llItemRaceLiveStatus -> {
                    pressedType = "1"
                    goToPassDetail(position)
                }
            }
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            pressedType = "2"
            passType = mAdapter.data[position].passType
            goToPassDetail(position)
        }
    }

    private fun goToPassDetail(position: Int) {
        gatherLiveStatus = mAdapter.data[position].gatherLiveStatus
        carLiveStatus = mAdapter.data[position].carLiveStatus
        backLiveStatus = mAdapter.data[position].backLiveStatus
        passStatus = mAdapter.data[position].passStatus.toString()
        passName = mAdapter.data[position].passName
        passId = mAdapter.data[position].id
        passCreateType = mAdapter.data[position].passCreateType
        val memberId: Int
        when (pressedType) {
            "1", "3" -> {
                //判断首先点击的直播按钮，然后没有任何直播的情况下 不做任何处理
                if (pressedType == "1" && gatherLiveStatus != 1 && carLiveStatus != 1 && backLiveStatus != 1) {
                    return
                }
                if (memberList.isEmpty()) {
                    RxToast.warning(getString(R.string.not_member_and_can_not_see_video))
                    return
                }
                if (memberList.size == 1) {
                    memberId = memberList[0].memberId
                    startActivityToPassDetail(memberId)
                } else {
                    showMemberDialog(memberList)
                }
            }

            "2", "4" -> {
                if (memberList.size == 1) {
                    memberId = memberList[0].memberId
                    startActivityToPassDetail(memberId)
                } else if (memberList.size > 1) {
                    showMemberDialog(memberList)
                } else {
                    startActivityToPassDetail(0)
                }
            }
        }
    }

    private fun getMemberCode(passId: Int) {
        showLoading(getString(R.string.loading))
        mViewModel.getMemberNum(passId.toString())
    }

    private fun showPlayBackDialog() {
        val dialog = RxDialogPlayBack(context)
        dialog.setTitle(getString(R.string.playback))
        dialog.setHideGather(gatherLiveStatus != 2)
        dialog.setHideCar(true)
        dialog.setHideHoming(backLiveStatus != 2)
        dialog.setGatherListener {
            startActivity<ActivityGatherLive>("passId" to passId, "title" to getString(R.string.gather_playback))
            dialog.dismiss()
        }
        dialog.setCarListener {
            startActivity<ActivityCarLiveAndPlayBack>("passId" to passId, "title" to getString(R.string.car_playback))
            dialog.dismiss()
        }
        dialog.setHomingListener {
            startActivity<ActivityGatherLive>("passId" to passId, "title" to getString(R.string.home_playback))
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /**  获取棚号  */
        mViewModel.memberNumResult.observe(viewLifecycleOwner) {
            if (it != null) {
                startActivity<ActivityPigeonGatheringDetail>(
                    "passId" to passId,
                    "title" to passName,
                    "memberCode" to it.memberNum,
                    "raceId" to mRaceId
                )
            }
        }
    }

    private fun showMemberDialog(list: ArrayList<VisitMemberListResponse.ListBean>) {
        val dialog = RxDialogMemberList(context)
        dialog.setAdapterData(list)
        dialog.setOnClickListener(object : RxDialogMemberList.OnItemClickListener {
            override fun onItemClick(position: Int, id: Int) {
                startActivityToPassDetail(id)
                dialog.dismiss()
            }
        })
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun startActivityToPassDetail(id: Int) {
        when (pressedType) {
            "1" -> {
                if (gatherLiveStatus == 1) {
                    startActivity<ActivityGatherLive>("passId" to passId, "title" to getString(R.string.Pigeon_collection_live))
                } else if (backLiveStatus == 1) {
                    startActivity<ActivityGatherLive>("passId" to passId, "title" to getString(R.string.Homing_live))
                } else if (carLiveStatus == 1) {
                    startActivity<ActivityGatherLive>("passId" to passId, "title" to getString(R.string.Live_stream_of_vehicle))
                }
            }

            "2" -> {
                startActivity<ActivityPassDetail>(
                    "passName" to passName,
                    "passId" to passId,
                    "data" to raceInfo,
                    "memberId" to id,
                    "orgName" to mOrgName,
                    "raceName" to mOrgRaceName,
                    "orgIcon" to mOrgIcon,
                    "raceId" to mRaceId,
                    "passStatus" to passStatus,
                    "passCreateType" to passCreateType,
                    "passType" to passType,
                )
            }

            "3" -> showPlayBackDialog()
            "4" -> getMemberCode(passId)
        }

    }

    companion object {

        fun newInstance(): FragmentOrgPass {
            return FragmentOrgPass()
        }
    }
}